#include <QFile>
#include <QDebug>
#include <QFileInfo>
#include <QSettings>
#include <QStringList>
#include <QCryptographicHash>
#include "CacheMap.h"

CacheMap::CacheMap()
{
    loadCache();
}

void CacheMap::loadCache()
{
    QSettings file("cache/index", QSettings::IniFormat);
    foreach(QString name, file.childGroups()){
        file.beginGroup(name);
        Cache c;
        c.md5 = file.value("md5").toString();
        c.filePath = file.value("file").toString();
        c.name = name;
        _map[c.filePath] = c;
        file.endGroup();
    }
}

bool CacheMap::isCached(const QFileInfo& fileName)
{
    if (_map.contains(fileName.absoluteFilePath())){
        if (md5(fileName.absoluteFilePath()) == _map[fileName.absoluteFilePath()].md5 && QFile::exists("cache/"+fileName.baseName()+".py"))
            return true;
    }
    return false;
}

QString CacheMap::md5(const QString& fileName)
{
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly)){
        QByteArray fileData = file.readAll();
        QByteArray hashData = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
        return hashData.toHex();
    }
    return "";
}

void CacheMap::addToCache(const QFileInfo& name)
{
    Cache c;
    c.md5 = md5(name.absoluteFilePath());
    c.filePath = name.absoluteFilePath();
    _map[name.absoluteFilePath()] = c;
    QSettings file("cache/index", QSettings::IniFormat);
    file.beginGroup(name.baseName());
    file.setValue("file", c.filePath);
    file.setValue("md5", c.md5);
    file.endGroup();
}

QString CacheMap::getCachedFile(const QFileInfo& fileName)
{
    return "cache/"+fileName.baseName()+".py";
}

bool CacheMap::contains(const QString& name)
{
    return QFile::exists("cache/"+name+".py");
}

QString CacheMap::findCachedByModuleName(const QString& modName)
{
    foreach(QString key, _map.keys()){
        if (_map[key].name == modName)
            return key;
    }
    return "";
}

